<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/10 010
 * Time: 15:28
 */

namespace App\Observer;


class WeatherData implements Subject
{
    private $observers = array();
    private $temperature;
    private $humidity;
    private $pressure;

    /*
    public function __construct()
    {
        $this->observers = array();
    }
    */

    public function registerObserver(Observer $observer)
    {
        // TODO: Implement registerObserver() method.
        $this->observers[] = $observer;
        //array_push($this->observers,$observer);

    }

    public function removeObserver(Observer $observer)
    {

        // TODO: Implement removeObserver() method.
        $key = array_search($observer,$this->observers);
        if(!($key === false))
        {
            unset($this->observers[$key]);
        }
        /*
        foreach($this->observers as $k=>$v) {
            if($observer == $v) unset($this->observers[$k]);
        }
        $this->observers = array_values($this->observers);
        */
    }

    public function notifyObservers()
    {
        // TODO: Implement notifyObservers() method.
        foreach($this->observers as $observer)
        {
            if($observer instanceof Observer) $observer->update($this->temperature, $this->humidity, $this->pressure);
        }
        /*
        foreach($this->observers as $k=>$v) {
            $observer = $v;
            $observer->update($this->temperature, $this->humidity, $this->pressure);
        }
        */
    }

    public function measurementsChanged()
    {
        $this->notifyObservers();
    }

    public function setMeasurements($temperature, $humidity, $pressure)
    {
        $this->temperature = $temperature;
        $this->humidity = $humidity;
        $this->pressure = $pressure;
        $this->measurementsChanged();
    }
}